﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.Text;
using SetpBySetp.Web.LiveSearchService;

namespace SetpBySetp.Web.WCF
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "LiveSearchWebService" in code, svc and config file together.
    public class LiveSearchWebService : ILiveSearchWebService
    {
        public SearchResultItem[] DoSearch(string query)
        {
            MSNSearchPortTypeClient client = new MSNSearchPortTypeClient();
            SearchRequest request = new SearchRequest();
            int arraySize = 1;
            SourceRequest[] sourceRequests = new SourceRequest[arraySize];

            sourceRequests[0] = new SourceRequest();
            sourceRequests[0].Source = SourceType.Web;

            request.Query = query;
            request.Requests = sourceRequests;

            request.AppID = "B83EAE57D9D17FAE04361FE136CBAD0894DD45BF";
            request.CultureInfo = "zh-CN";
            SearchResponse searchResponse;

            searchResponse = client.Search(request);

            List<SearchResultItem> lists = new List<SearchResultItem>();
            foreach(SourceResponse sourceResponse in searchResponse.Responses)
            {
                Result[] sourceResults = sourceResponse.Results;
                foreach(Result sourceResult in sourceResults)
                {
                    SearchResultItem item = new SearchResultItem();
                    if(!string.IsNullOrEmpty(sourceResult.Title))
                    {
                        item.Title = sourceResult.Title;
                    }
                    if(!string.IsNullOrEmpty(sourceResult.Url))
                    {
                        item.Url = sourceResult.Url;
                    }
                    if(!string.IsNullOrEmpty(sourceResult.Description))
                    {
                        item.Description = sourceResult.Description;
                    }
                    lists.Add(item);
                }
            }
            return lists.ToArray();
        }
    }
}
